package com.zmjmall.demo.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.zmjmall.demo.api.ProductService;
import com.zmjmall.demo.api.ShopService;
import com.zmjmall.demo.constant.GlobalConstant;
import com.zmjmall.demo.dto.ProductDTO;
import com.zmjmall.demo.enums.ResultEnum;
import com.zmjmall.demo.model.Product;
import com.zmjmall.demo.model.Shop;
import com.zmjmall.demo.utils.ResultVOUtil;
import com.zmjmall.demo.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


/**
 * 商品信息控制层
 *
 * @author zmj
 * @version 2018/6/29
 */
@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController extends BaseController {

    @Reference
    private ProductService productService;

    @Reference
    private ShopService shopService;

    /**
     * 返回所有商品
     * @return
     */
    @GetMapping
    @ResponseBody
    public ResultVO<Product> findAll() {
        List<Product> list = productService.findAll();
        return ResultVOUtil.success(list);
    }

    /**
     * 通过ID查询商品信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ResponseBody
    public ResultVO<Product> findById(@PathVariable("id") String id) {
        return ResultVOUtil.success(productService.findById(id));
    }

    /**
     * 创建商品
     * @param productDTO
     * @return
     */
    @PostMapping
    @ResponseBody
    public ResultVO<Product> createProduct(String userId,@Valid ProductDTO productDTO){
        //http://localhost:8082/product?attributeValues=11:3/4,12:1/2&productName=测试产品11&categoryId=101010&brandId=123&productType=1
        Shop shop = shopService.findByUserId(userId);

        if(shop == null) {
            return ResultVOUtil.error(ResultEnum.SHOP_NOTCREATE);
        }else if(shop.getAudit() == GlobalConstant.SHOP_AUDIT){
            return ResultVOUtil.error(ResultEnum.SHOP_WAIT_AUDITING);
        }

        productDTO.setShopId(shop.getId());

        int insert = productService.insert(productDTO);

        if(insert == 1) {
            return ResultVOUtil.success(ResultEnum.SUCCESS);
        }
        return ResultVOUtil.error(ResultEnum.RESTFUL_API_ERROR);
    }

}
